﻿menu_click
var connection;
var myFriend;

$(function () {
    $("#menu").menu();
    $("#tabs").tabs();
    $("#fieldset_mainchat").hide();
    $("#chat-container").hide();
    $("#dialog-message").dialog({
        modal: true,
        buttons: {
            Ok: function () {
                $(this).dialog("close");
            }
        }
    });

    $("#dialog-confirm").dialog({
        resizable: false,
        height: 200,
        modal: true,
        buttons: {
            "Đồng ý": function () {
                $(this).dialog("close");
                $.post("http://localhost:3338/api/chat?addFriend=aa&taikhoan=" + myFriend.TaiKhoan + "&taikhoanban=" + myFriend.TaiKhoanBan, null, function (mydata) {

                    if (mydata != null) {
                        $("#menu").empty();
                        mydata.forEach(function (value) {
                            if (value.TinhTrang == true) {

                                if (value.OpenID)
                                    user_avatar = "http://img.msg.yahoo.com/avatar.php?yids=pre_email&format=gif".replace("pre_email", user_avatar);
                                else
                                    user_avatar = "http://localhost:3338/hinhanh/' + value.TaiKhoan + '.jpg";
                                $("#menu").append('<li><a href="#' + value.TaiKhoan + '" onclick="return menu_click(&#39;' + value.TaiKhoan + '&#39;)"><img class="avatar" src=' + user_avatar + ' onError="return ImgError(this)" />  ' + value.TaiKhoan + '</a></li>');
                                $("#menu").menu("refresh");
                            }
                            else {
                                $("#menu").append('<li><a class="offline" href="#' + value.TaiKhoan + '" onclick="return menu_click(&#39;' + value.TaiKhoan + '&#39;)"><img class="avatar" src="HinhAnh/Offline.jpg" />  ' + value.TaiKhoan + '</a></li>');
                                $("#menu").menu("refresh");
                            }
                        });

                        var message = {
                            Type: 1,
                            TaiKhoanGui: myFriend.TaiKhoan,
                            TaiKhoanNhan: myFriend.TaiKhoanBan,
                            NoiDung: ""
                        }
                        connection.send(window.JSON.stringify(message));
                    }
                }, "json");


            },
            "Hủy": function () {
                $(this).dialog("close");
            }
        }
    });

    $("#dialog-message").dialog("close");
    $("#dialog-confirm").dialog("close");

    $("#div-logout").hide();
    $("#add-friend").hide();
});


//setInterval(function () {
//    $.getJSON("http://localhost:3338/api/chat?msg=" + $("#account_user").text(), null, function (data) {
//        //alert(data);
//        if (data != null) {
//            if (document.getElementById(data.TaiKhoanGui)) {
//                $('#' + data.TaiKhoanGui).append('<p>' + data.TaiKhoanGui + ': ' + data.NoiDung + '</p>');
//            }
//            else {
//                $("#tab-title").append('<li><a href="#' + data.TaiKhoanGui + '">' + data.TaiKhoanGui + '</a><span class="ui-icon ui-icon-close">Remove Tab</span></li>');
//                $("#tabs").append('<div class="chat-window" id="' + data.TaiKhoanGui + '"></div>');
//                $("#tabs").tabs("refresh");
//                $('#' + data.TaiKhoanGui).append('<p>' + data.TaiKhoanGui + ': ' + data.NoiDung + '</p>');
//            }
//            $(".chat-window").scrollTop($(".chat-window")[0].scrollHeight);
//        }
//    });
//}, 1000);

//setInterval(function () {
//    var user = $("#account_user").text();
//    if (user != "") {
//        //alert($("#account_user").text());

//    }
//}, 5000);

function ImgError(source) {
    source.src = "Hinhanh/noimage.jpg";
    source.onerror = "";
    return true;
}

window.onbeforeunload = function (e) {

    var acc = {
        TaiKhoan: $("#account_user").text(),
        MatKhau: "",
        TinhTrang: true
    }

    $.post("http://localhost:3338/api/chat?logout=", acc, function (data) {
        if (data == 1) {
            $("#account_user").empty();
            $("#menu").empty();
            $("#menu").menu("refresh");
            $("#tab-title").empty();
            $("#tabs").children("div").remove();
        }
    }, "json");
};

// close icon: removing the tab on click
$("#tabs span.ui-icon-close").live("click", function () {
    var panelId = $(this).closest("li").remove().attr("aria-controls");
    $("#" + panelId).remove();
    tab_counters--;
    if (tab_counters < 0)
        $("#chat-container").hide();
    else
        $("#tabs").tabs("select", 0);
    //tabs.tabs("refresh");
});
function hello(value) {

    alert(value);
}
var OpenID = false;
function Button_login_onclick() {
    var userText = $("#TextBox_UserName").val();
    var passText = $("#TextBox_Passwork").val();
    OpenID = false;
    callGetFriends(userText, passText, OpenID);

}
var user_avatar = "";
function Login_OpenID(userText) {
    var passText = "123";
    OpenID = true;
    user_avatar = getPreEmail(userText);
    callGetFriends(userText, passText, OpenID, user_avatar);

}
function getPreEmail(userText) {
    //user_avatar = userText.substring(0, userText.indexOf("@"));
    user_avatar = userText;
    return user_avatar;
}

function callGetFriends(userText, passText, OpenID, user_avatar) {
    $.getJSON("http://localhost:3338/api/chat?acc=" + userText + "&pass=" + passText + "&OpenID=" + OpenID, null, function (data) {
        if (data != null) {
            $("#account_user").text(userText);

            document.cookie = 'username=' + $("#account_user").text();


            var host = "ws://localhost:3338/ChatHandler.ashx";
            connection = new WebSocket(host);

            connection.onmessage = function (msg) {
                var data = window.JSON.parse(msg.data);
                var myresult;
                switch (data.Type) {
                    
                    case 0: {
                        if (document.getElementById(data.TaiKhoanGui)) {
                            CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: data.NoiDung }), function (myresult) {
                                $('#' + data.TaiKhoanGui).append('<p>' + data.TaiKhoanGui + ': ' + myresult.d + '</p>');
                            });
                           
                        }
                            //nhan tin nhan truc tiep
                        else {
                            $("#chat-container").show();
                            tab_counters++;
                            $("#tab-title").append('<li><a href="#' + data + '">' + data + '</a><span class="ui-icon ui-icon-close">Remove Tab</span></li>');
                            $("#tabs").append('<div class="chat-window" id="' + data + '"></div>');
                            $("#tabs").tabs("refresh");
                            $("#tabs").tabs("select", tab_counters);
                            CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: data.NoiDung }), function (myresult) {
                                $('#' + data.TaiKhoanGui).append('<p>' + data.TaiKhoanGui + ': ' + myresult.d + '</p>');
                            });
                            ///cap nhat url avatar o day
                        }
                       
                        $(".chat-window").scrollTop($(".chat-window")[0].scrollHeight);
                    } break;
                    case 1: {
                        
                        $.getJSON("http://localhost:3338/api/chat?acc=" + $("#account_user").text(), null, function (result) {
                            if (result != null) {
                                $("#menu").empty();
                                result.forEach(function (value) {
                                    //dang off -> on
                                    //alert(value.TaiKhoan + "-" + value.TinhTrang + "-" + value.OpenID);
                                    if (value.TinhTrang == true) {
                                        if (value.OpenID == true)
                                            user_avatar = "http://img.msg.yahoo.com/avatar.php?yids=pre_email&format=gif".replace("pre_email", value.TaiKhoan);
                                        else
                                            user_avatar = "http://localhost:3338/hinhanh/' + value.TaiKhoan + '.jpg";
                                        
                                        $("#menu").append('<li><a href="#' + value.TaiKhoan + '" onclick="return menu_click(&#39;' + value.TaiKhoan + '&#39;)"><img class="avatar" src=' + user_avatar + ' onError="return ImgError(this)" />  ' + value.TaiKhoan + '</a></li>');
                                        $("#menu").menu("refresh");
                                    }
                                        //nguoc lai
                                    else {
                                        $("#menu").append('<li><a class="offline" href="#' + value.TaiKhoan + '" onclick="return menu_click(&#39;' + value.TaiKhoan + '&#39;)"><img class="avatar" src="HinhAnh/Offline.jpg" />  ' + value.TaiKhoan + '</a></li>');
                                        $("#menu").menu("refresh");
                                    }
                                });
                            }
                        });
                    } break;
                    case 2: {
                        //yeu cau ket ban khi ca 2 cung online
                        myFriend = {
                            TaiKhoan: data.TaiKhoanNhan,
                            TaiKhoanBan: data.TaiKhoanGui,
                        }
                        $("#FriendRequest").text("");
                        $("#FriendRequest").append(data.TaiKhoanGui + ' muốn kết bạn với bạn');
                        $("#dialog-confirm").dialog("open");
                    } break;
                    case 3: {
                        var offMsg = window.JSON.parse(data.NoiDung);
                        offMsg.forEach(function (value) {
                            //
                            if (value.NoiDung != "nagisafurukawachan") {
                                if (document.getElementById(value.TaiKhoanGui)) {
                                    //$('#' + value.TaiKhoanGui).append('<p>' + value.TaiKhoanGui + ': ' + value.NoiDung + '</p>');
                                    CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: data.NoiDung }), function (myresult) {
                                        $('#' + data.TaiKhoanGui).append('<p>' + data.TaiKhoanGui + ': ' + myresult.d + '</p>');
                                    });
                                }
                                else {
                                    // goi tin nhan offline
                                    $("#chat-container").show();
                                    tab_counters++;
                                    $("#tab-title").append('<li><a href="#' + value.TaiKhoanGui + '">' + value.TaiKhoanGui + '</a><span class="ui-icon ui-icon-close">Remove Tab</span></li>');
                                    $("#tabs").append('<div class="chat-window" id="' + value.TaiKhoanGui + '"></div>');
                                    $("#tabs").tabs("refresh");
                                    $("#tabs").tabs("select", tab_counters);
                                    //$('#' + value.TaiKhoanGui).append('<p>' + value.TaiKhoanGui + ': ' + value.NoiDung + '</p>');
                                    CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: value.NoiDung }), function (myresult) {
                                        $('#' + value.TaiKhoanGui).append('<p>' + value.TaiKhoanGui + ': ' + myresult.d + '</p>');
                                    });
                                }
                                $(".chat-window").scrollTop($(".chat-window")[0].scrollHeight);
                            }
                                //yeu cau ket ban voi nguoi dang offline
                            else {
                                
                                myFriend = {
                                    TaiKhoan: value.TaiKhoanNhan,
                                    TaiKhoanBan: value.TaiKhoanGui,
                                }
                                $("#FriendRequest").text("");
                                $("#FriendRequest").append(value.TaiKhoanGui + ' muốn kết bạn với bạn');
                                $("#dialog-confirm").dialog("open");
                            }
                        });
                    }

                }
            }

            data.forEach(function (value) {
                if (value.TinhTrang == true) {
                    user_avatar = getPreEmail(value.TaiKhoan);
                    if (value.OpenID)
                        user_avatar = "http://img.msg.yahoo.com/avatar.php?yids=pre_email&format=gif".replace("pre_email", user_avatar);
                    else
                        user_avatar = "http://localhost:3338/hinhanh/' + value.TaiKhoan + '.jpg";
                    $("#menu").append('<li><a href="#' + value.TaiKhoan + '" onclick="return menu_click(&#39;' + value.TaiKhoan + '&#39;)"><img class="avatar" src=' + user_avatar + ' onError="return ImgError(this)" />  ' + value.TaiKhoan + '</a></li>');
                    $("#menu").menu("refresh");
                }
                else {
                    $("#menu").append('<li><a class="offline" href="#' + value.TaiKhoan + '" onclick="return menu_click(&#39;' + value.TaiKhoan + '&#39;)"><img class="avatar" src="HinhAnh/Offline.jpg" />  ' + value.TaiKhoan + '</a></li>');
                    $("#menu").menu("refresh");
                }
            });


            $("#div-logout").show();
            $("#loginContainer").hide();
            $("#fieldset_mainchat").show();
            $("#add-friend").show();
            user_avatar = getPreEmail(userText);
            if (OpenID)
                user_avatar = "http://img.msg.yahoo.com/avatar.php?yids=pre_email&format=gif".replace("pre_email", user_avatar);
            else
                user_avatar = "http://localhost:3338/hinhanh/" + userText + ".jpg";
            $("#hinh-dai-dien").append('<img class="useravatar" src=' + user_avatar + ' onError="return ImgError(this)" />');
        }
        else {
            alert("Tài khoản hoặc mật khẩu không chính xác");
        }
    });
}
var tab_counters = -1;
function menu_click(data) {
    $("#chat-container").show();
    $("#textbox_send").focus();
    var idchecker = document.getElementById(data);
    if (idchecker == null) {
        tab_counters++;
        $("#tab-title").append('<li><a href="#' + data + '">' + data + '</a><span class="ui-icon ui-icon-close">Remove Tab</span></li>');
        $("#tabs").append('<div class="chat-window" id="' + data + '"></div>');
        $("#tabs").tabs("refresh");
        $("#tabs").tabs("select", tab_counters);
    }
}

function Button_send_onclick() {
    var text = $("#textbox_send").val();
    
    var myresult;
    CallServerFunction("Default.aspx/getHello", JSON.stringify({ str: text }), function (myresult) {
        if (text != "")
            $('#' + id).append('<p>' + $("#account_user").text() + ': ' + myresult.d + '</p>');
    });
    var id = $(".ui-state-active").children().first().text();

    var message = {
        Type: 0,
        TaiKhoanGui: $("#account_user").text(),
        TaiKhoanNhan: id,
        NoiDung: text
    }
    //$.post("http://localhost:3338/api/chat?SendMsg=", message, function (data) {
    //    if (data == -1)
    //        alert("Có lỗi");
    //}, "json");
    connection.send(window.JSON.stringify(message));

    $(".chat-window").scrollTop($(".chat-window")[0].scrollHeight);
    $("#textbox_send").val("");
}

function Button_AddFriend_onclick() {

    var message = {
        Type: 2,
        TaiKhoanGui: $("#account_user").text(),
        TaiKhoanNhan: $("#text_AddFriend").val(),
        NoiDung: "nagisafurukawachan"
    }

    connection.send(window.JSON.stringify(message));

    $("#dialog-message").dialog("open");
}

function Button_logout_onclick() {

    connection.close();

    $("#account_user").empty();
    $("#menu").empty();
    $("#menu").menu("refresh");
    $("#tab-title").empty();
    $("#tabs").children("div").remove();

    //$.post("http://localhost:3338/api/chat?logout=", acc, function (data) {
    //    if (data == 1) {
    //        $("#account_user").empty();
    //        $("#menu").empty();
    //        $("#menu").menu("refresh");
    //        $("#tab-title").empty();
    //        $("#tabs").children("div").remove();
    //    }
    //}, "json");

    $("#div-logout").hide();
    $("#loginContainer").show();
    $("#add-friend").hide();
    $("#fieldset_mainchat").hide();
    $("#hinh-dai-dien").empty();
}

function Button_deleteFriend_onclick() {
    var id = $(".ui-state-active").children().first().text();
    var myFriend = {
        TaiKhoan: $("#account_user").text(),
        TaiKhoanBan: id
    }

    $.post("http://localhost:3338/api/chat?deleteFriend=a&taikhoan=" + myFriend.TaiKhoan + "&taikhoanban=" + myFriend.TaiKhoanBan, null, function (data) {
        if (data != null) {
            $("#menu").empty();
            data.forEach(function (value) {
                if (value.TinhTrang == true) {
                    $("#menu").append('<li><a href="#' + value.TaiKhoan + '" onclick="return menu_click(&#39;' + value.TaiKhoan + '&#39;)"><img class="avatar" src="http://localhost:3338/hinhanh/' + value.TaiKhoan + '.jpg" onError="return ImgError(this)" />  ' + value.TaiKhoan + '</a></li>');
                    $("#menu").menu("refresh");
                }
                else {
                    $("#menu").append('<li><a class="offline" href="#' + value.TaiKhoan + '" onclick="return menu_click(&#39;' + value.TaiKhoan + '&#39;)"><img class="avatar" src="HinhAnh/Offline.jpg" />  ' + value.TaiKhoan + '</a></li>');
                    $("#menu").menu("refresh");
                }
            });
        }
    }, "json");
}
function CallServerFunction(StrPriUrl, ObjPriData, CallBackFunction) {

    $.ajax({
        type: "post",
        url: StrPriUrl,
        contentType: "application/json; charset=utf-8",
        data: ObjPriData,
        dataType: "json",
        success: function (result) {
            if (CallBackFunction != null && typeof CallBackFunction != 'undefined') {
                CallBackFunction(result);
            }

        },
        error: function (result) {
            alert('error occured');
            alert(result.responseText);
            window.location.href = "FrmError.aspx?Exception=" + result.responseText;
        },
        async: true
    });
}

function emoticons_click(result)
{
    //alert(result.alt);
    //document.getElementById('textbox_send').innerHTML += result.alt;
    var str = $("#textbox_send").val();
    $("#textbox_send").val(str + result.alt);
    //document.getElementById('id_panel_emoticons').style.visibility = "hidden";
    document.getElementById('id_panel_emoticons').style.display = "none";
}
function main_emoticons_click() {
    //document.getElementById('id_panel_emoticons').style.visibility = "visible";
    if (document.getElementById('id_panel_emoticons').style.display == "block")
        document.getElementById('id_panel_emoticons').style.display = "none"
    else
    document.getElementById('id_panel_emoticons').style.display = "block";
}
function inputKeyDown(evt, textarea) {
    if (evt.keyCode == 13) {
        Button_send_onclick();
        return false;
    }
}